<template>
  <view class="container">
    <view class="unp-header">
      <u-swiper :list="swiperImageList"></u-swiper>
    </view>
    <u-notify ref="uNotify"></u-notify>
    <u--form labelPosition="left" :model="formData" ref="form">
      <uni-section class="form-section" title="位置信息" type="line">
        <u-form-item class="form-item" label="出发地" labelWidth="80" prop="startAddress" borderBottom ref="start-address">
          <u-input type="text" maxlength="10" v-model="formData.startAddress" clearable focus
            :placeholder="startAddressPlaceholder" border="none" @focus="selectAdresss('start')"></u-input>
        </u-form-item>
        <u-form-item class="form-item" label="目的地" labelWidth="80" prop="endAddress" borderBottom>
          <u-input type="text" maxlength="20" v-model="formData.endAddress" clearable ref="end-adress"
            :placeholder="endAddressPlaceholder" border="none" @focus="selectAdresss('end')"></u-input>
        </u-form-item>
        <u-picker :show="showAddressPicker" :title="addressPickTitle" ref="addressPicker" :columns="addressColumns0"
          @cancel="showAddressPicker=false" @change="addressChangeHandler" @confirm="addressConfirm"
          @close="showAddressPicker=false" closeOnClickOverlay></u-picker>
      </uni-section>

      <uni-section class="form-section" title="行程信息" type="line" v-if="showJourneySection">
        <u-form-item class="form-item" label="出发时间" labelWidth="80" prop="startTime" borderBottom ref="start-time">
          <u-input type="text" maxlength="20" v-model="formData.startTime" clearable :placeholder="startTimePlaceholder"
            border="none" @focus="showStartTimePicker=true;hideKeyboard()"></u-input>
          <u-picker :show="showStartTimePicker" :title="startTimePlaceholder" ref="startTimePicker"
            :columns="startTimeColumns0" @cancel="showStartTimePicker=false" @change="startTimeChangeHandler"
            @confirm="startTimeConfirm" @close="showStartTimePicker=false" closeOnClickOverlay
            :defaultIndex="[0,0]"></u-picker>
        </u-form-item>
        <u-form-item class="form-item" label="乘车人数" labelWidth="80" prop="personNum" borderBottom ref="person-num">
          <u-input type="text" maxlength="20" v-model="formData.personNum" clearable :placeholder="personNumPlaceholder"
            border="none" @focus="showPersonNumPicker=true"></u-input>
          <u-picker :show="showPersonNumPicker" :title="personNumPlaceholder" ref="personNumPicker"
            :columns="personNumColumns0" @cancel="personNumPicker=false" @confirm="personNumConfirm" keyName="label"
            @close="showPersonNumPicker=false" closeOnClickOverlay></u-picker>
        </u-form-item>
        <u-form-item class="form-item" label="携带物品" labelWidth="80" prop="appendices" borderBottom ref="appendices">
          <u-input type="text" maxlength="20" v-model="formData.appendices" clearable placeholder="是否有携带物品"
            border="none" @focus="showAppendicesPicker=true"></u-input>
          <u-picker :show="showAppendicesPicker" :title="appendicesPlaceholder" ref="appendicesPicker"
            :columns="appendicesColumns0" @cancel="showAppendicesPicker=false" @confirm="appendicesConfirm"
            @close="showAppendicesPicker=false" closeOnClickOverlay :defaultIndex="[0,0]"></u-picker>
        </u-form-item>
        <u-button type="primary" text="发布" customStyle="margin-top: 50px" @click="submit"></u-button>
      </uni-section>
    </u--form>

  </view>
</template>

<script>
  import {
    createOrder,
    queryOrder
  } from '../../api/pinche';
  import config from '@/common/config';
  export default {
    data() {
      return {
        swiperImageList: [], //轮播图
        addressColumns0: [], //地址选择第一列
        addressColumns1: [], //地址选择第2列
        showAddressPicker: false,
        addressPickTitle: '',
        startAddressPlaceholder: '你从哪里出发？',
        endAddressPlaceholder: '你要去哪儿？',
        addressType: 'start',
        startTimePlaceholder: '请选择出发时间',
        startTimeColumns0: [],
        showStartTimePicker: false,
        personNumPlaceholder: '请选择乘车人数',
        showPersonNumPicker: false,
        personNumColumns0: [
          [{
            label: '1人',
            id: 1
          }, {
            label: '2人',
            id: 2
          }, {
            label: '3人',
            id: 4
          }, {
            label: '4人',
            id: 4
          }, {
            label: '5人',
            id: 5
          }, {
            label: '6人',
            id: 6
          }]
        ],
        showAppendicesPicker: false,
        appendicesPlaceholder: '是否有携带物品？',
        appendicesColumns0: [
          ['没有', '有']
        ],
        showJourneySection: false,
        formData: {
          startAddress: '',
          endAddress: '',
          startTime: '现在',
          personNum: '1人',
          appendices: '没有'
        }
      }
    },
    onLoad() {
      if (!this.$store.getters.hasLogin) {
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },
    onReady() {
      this.loadSwiperImage();
      this.loadAddress();
      this.loadStartTime();
    },
    //去掉顶部左侧返回按钮
    mounted() {
      var a = document.getElementsByClassName('uni-page-head-hd')[0]
      a.style.display = 'none';
    },
    methods: {
      loadSwiperImage() {
        this.swiperImageList = [
          'https://cdn.uviewui.com/uview/swiper/swiper1.png',
          'https://cdn.uviewui.com/uview/swiper/swiper2.png',
          'https://cdn.uviewui.com/uview/swiper/swiper3.png',
        ];
      },
      loadAddress() {
        //todo 网络请求
        this.addressColumns0 = [
          ['中国', '美国'],
          ['深圳', '厦门', '上海', '拉萨']
        ];
        this.addressColumns1 = [
          ['深圳', '厦门', '上海', '拉萨'],
          ['得州', '华盛顿', '纽约', '阿拉斯加']
        ];
      },
      selectAdresss(type) {
        if (type == 'start') {
          this.addressType = 'start';
          this.addressPickTitle = "请选择" + this.startAddressPlaceholder;
        }
        if (type == 'end') {
          if (!this.formData.startAddress) {
            this.openNotify('请先选择出发地', 'error')
            return;
          }
          this.addressType = 'end';
          this.addressPickTitle = "请选择" + this.endAddressPlaceholder;
        }
        this.showAddressPicker = true;
        uni.hideKeyboard();
      },
      addressChangeHandler(e) {
        const {
          columnIndex,
          value,
          values, // values为当前变化列的数组内容
          index,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.addressPicker
        } = e
        // 当第一列值发生变化时，变化第二列(后一列)对应的选项
        if (columnIndex === 0) {
          // picker为选择器this实例，变化第二列对应的选项
          picker.setColumnValues(1, this.addressColumns1[index])
        }
      },
      addressConfirm(e) {
        this.showAddressPicker = false;
        const {
          columnIndex,
          value,
          values
        } = e;
        if (this.addressType == 'start') {
          this.formData.startAddress = value.join('.');
          if (this.formData.startAddress == this.formData.endAddress) {
            this.openNotify('出发地不能跟目的地相同', 'error')
            this.formData.startAddress = '';
            return;
          }
          let _this = this;
          setTimeout(function() {
            _this.selectAdresss('end');
          }, 300)
        }
        if (this.addressType == 'end') {
          this.formData.endAddress = value.join('.');
          if (this.formData.startAddress == this.formData.endAddress) {
            this.openNotify('目的地不能跟出发地相同', 'error')
            this.formData.endAddress = '';
            return;
          }
          this.showJourneySection = true;
          this.showStartTimePicker = true;
        }
      },
      loadStartTime() {
        this.startTimeColumns0 = [
          ['现在', '今天', '明天', '后天'],
          ['--'],
          []
        ];
      },
      selectStartTime() {
        this.showStartTimePicker = true;
        uni.hideKeyboard();
      },
      startTimeChangeHandler(e) {
        var today = new Date();
        const {
          columnIndex,
          value,
          values, // values为当前变化列的数组内容
          index,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.startTimePicker,
          nowHour = today.getHours(),
          nowMinutes = today.getMinutes(),
          minHour = 8,
          maxHour = 18
        } = e
        // 当第一列值发生变化时，变化第二列(后一列)对应的选项
        if (columnIndex === 0) {
          // picker为选择器this实例，变化第二列对应的选项
          if (index == 0) {
            picker.setColumnValues(1, ['--'])
            picker.setColumnValues(2, [])
          } else if (index == 1) { //今天
            if (nowHour > maxHour || nowHour < minHour) {
              picker.setColumnValues(1, ['不在服务时间']);
              picker.setColumnValues(2, []);
            } else {
              var startTimeColumns1_item = [];
              for (var i = nowHour; i <= maxHour; i++) {
                startTimeColumns1_item.push(i + '点');
              }
              picker.setColumnValues(1, startTimeColumns1_item);
              var startTimeColumns2_item = [];

              for (var i = Math.ceil(nowMinutes / 10) * 10; i <= 59;) {
                startTimeColumns2_item.push(i + '分');
                i += 10;
              }
              picker.setColumnValues(2, startTimeColumns2_item)
            }
          } else {
            var startTimeColumns1_item = [];
            for (var i = minHour; i <= maxHour; i++) {
              startTimeColumns1_item.push(i + '点');
            }
            picker.setColumnValues(1, startTimeColumns1_item);
            var startTimeColumns2_item = [];
            for (var i = 0; i <= 59;) {
              startTimeColumns2_item.push(i + '分');
              i += 10;
            }
            picker.setColumnValues(2, startTimeColumns2_item)
          }
        }
      },
      startTimeConfirm(e) {
        const {
          columnIndex,
          value,
          values
        } = e;
        if (value.includes('不在服务时间')) {
          this.openNotify('无效出发时间', 'error')
          this.showStartTimePicker = true;
        } else {
          this.formData.startTime = value.filter(v => '--' != v).join('');
          this.showStartTimePicker = false;
          this.showPersonNumPicker = true;
        }
      },
      personNumConfirm(e) {
        const {
          columnIndex,
          value,
          values
        } = e;
        this.formData.personNum = value[0].id;
        this.showPersonNumPicker = false;
        this.showAppendicesPicker = true;
      },
      appendicesConfirm(e) {
        const {
          columnIndex,
          value,
          values
        } = e;
        this.formData.appendices = value.join();
        this.showAppendicesPicker = false;
      },
      hideKeyboard() {
        uni.hideKeyboard()
      },
      openNotify(message, type) {
        this.$refs.uNotify.show({
          message: message,
          type: type,
          fontSize: 15,
          duration: 3000,
          safeAreaInsetTop: true
        })
      },
      submit() {
        //TODO 提交后台
        console.log('formData' + JSON.stringify(this.formData))
        this.formData.appId = config.appId;
        createOrder(this.formData).then(res => {
          uni.hideLoading()
          this.openNotify('发布成功', 'success')
          console.log(res)
          uni.redirectTo({
          	 url: '/pages/pinche/detail?id='+res.data
          });
        })
      },

    }
  }
</script>

<style lang="scss" scoped>
  .unp-header {
    padding: 40rpx;
  }

  .form-section {
    padding-left: 17rpx;

    .form-item {
      padding-left: 17rpx;
    }
  }
</style>
